package com.niudong.esdemo.Demo.IO.demo10_扩展知识_理解;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class Demo implements AutoCloseable{
    @Override
    public void close() throws Exception {
        System.out.println("看看我执行了吗? ");
    }
}

//补充知识三: IO流的标准异常处理代码.
public class Demo03 {
    public static void main(String[] args) {
        //方式一: JDK1.7以前, try.catch嵌套.
        //method01();

        //方式二: JDK1.7以后, try.with.resources语句.
        //特点: 写在try小括号中的对象, 会在try大括号中的内容执行完毕后, 自动释放.
        //原因: 写在try小括号中的对象所在的类, 必须实现一个接口, AutoCloseable接口, 重写close()方法.
        try (
                FileReader fr = new FileReader("./day05/data/1.txt");
                FileWriter fw = new FileWriter("./day05/data/5.txt");
                Demo d = new Demo();
        ) {
            System.out.println("1");
            int len = 0;
            char[] chs = new char[1024];
            while ((len = fr.read(chs)) != -1) {
                //5. 将读取到的数据写入到 指定的目的地文件中.
                fw.write(chs, 0, len);
            }
            System.out.println("2");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void method01() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //System.out.println(1 / 0);
            fr = new FileReader("./day05/data/1.txt");
            fw = new FileWriter("./day05/data/5.txt");
            int len = 0;
            char[] chs = new char[1024];
            while ((len = fr.read(chs)) != -1) {
                fw.write(chs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6. 释放资源.
            try {
                if (fr != null) {
                    fr.close();
                    fr = null;   //GC会优先回收.
                }
                System.out.println("fr 关闭了.");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fw != null) {
                        fw.close();
                        fw = null;
                    }
                    System.out.println("fw 关闭了.");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
